<template>
    <div class="container">
        <div class="main">
            <div class="header">
                <el-button type="primary" @click="openDialog(null)">新建</el-button>
                <el-button type="success" @click="importData">导入</el-button>
                <el-button type="danger" @click="batchDelete">批量删除</el-button>
                <el-select v-model="selectedFilter" @change="handleFilterChange">
                    <el-option label="启用" value="1"></el-option>
                    <el-option label="禁用" value="0"></el-option>
                </el-select>
                <el-input placeholder="请输入关键字搜索" v-model="searchTable" />
                <el-button type="info" @click="query" style="background-color: orange;">查询</el-button>
                <el-button type="info" @click="reset">重置</el-button>
            </div>
            <el-table :empty-text="emptyText" :data="tableData" border class="eltable"
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column type="index"  label="序号" width="60"></el-table-column>
                <el-table-column prop="zjxm_id" v-if="false"></el-table-column>
                <el-table-column prop="zjxm_code" label="检验项目编码" width="200"></el-table-column>
                <el-table-column prop="zjxm_name" label="检验项目名称"></el-table-column>
                <el-table-column prop="zjxm_sx" v-if="false"></el-table-column>
                <el-table-column prop="zjxm_sx_name" label="检验项目属性"></el-table-column>
                <el-table-column prop="zjxm_max" v-if="false"></el-table-column>
                <el-table-column prop="zjxm_min" v-if="false"></el-table-column>
                <el-table-column prop="zjxm_dw" v-if="false"></el-table-column>
                <el-table-column prop="zjxm_dw_name" label="单位"></el-table-column>
                <el-table-column prop="zjxm_jybz" label="检验标准"></el-table-column>
                <el-table-column prop="zjxm_remark" label="备注" width="160"></el-table-column>
                <el-table-column label="启用" width="70">
                    <template #default="{ row }">
                        <el-switch v-model="row.zjxm_state" :active-value="1" :inactive-value="0"
                            @change="updateState(row)"></el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="120">
                    <template #default="{ row }">
                        <el-button type="text" @click="openDialog(row)">编辑</el-button>
                        <el-button type="text" @click="deleteRow(row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 新增/编辑弹窗 -->
        <el-dialog v-model="dialogVisible" :title="dialogTitle" width="700px" @close="resetForm">
            <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px">
                <el-row gutter="20">
                    <el-col :span="12">
                        <el-form-item label="项目编码" prop="zjxm_code">
                            <el-input v-model="formData.zjxm_code"  :readonly="true"  />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="项目名称：" prop="zjxm_name">
                            <el-input v-model="formData.zjxm_name" placeholder="请输入名称" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row gutter="20">
                    <el-col :span="12">
                        <el-form-item label="项目属性：" prop="zjxm_sx">
                            <el-select v-model="formData.zjxm_sx" placeholder="请选择属性">
                                <el-option v-for="item in SXOptions" :key="item.dictionary_id"
                                    :label="item.dictionary_name" :value="item.dictionary_id" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row gutter="20">
                    <el-col :span="24">
                        <el-form-item label="检验标准：" prop="zjxm_jybz">
                            <el-input v-model="formData.zjxm_jybz" placeholder="请输入检验标准" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row gutter="20">
                    <el-col :span="12">
                        <el-form-item label="项目最大值：" prop="zjxm_max">
                            <el-input v-model="formData.zjxm_max" placeholder="请输入最大值" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="项目最小值：" prop="zjxm_min">
                            <el-input v-model="formData.zjxm_min" placeholder="请输入最小值" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row gutter="20">
                    <el-col :span="12">
                        <el-form-item label="项目单位：" prop="zjxm_dw">
                            <el-select v-model="formData.zjxm_dw" placeholder="请选择单位">
                                <el-option v-for="item in DWOptions" :key="item.dw_id" :label="item.dw_name"
                                    :value="item.dw_id" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row gutter="20">
                    <el-col :span="24">
                        <el-form-item label="备注：" prop="zjxm_remark">
                            <el-input v-model="formData.zjxm_remark" placeholder="请输入备注" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitForm">保存</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';

export default {
    setup() {
        const emptyText = '暂无数据';
        const selectedFilter = ref('1');
        const searchTable = ref('');
        const tableData = ref([]);
        const multipleSelection = ref([]);
        const dialogVisible = ref(false);
        const dialogTitle = ref('新增检验项目');
        const formRef = ref(null);
        const formData = ref({
            zjxm_code: '',
            zjxm_name: '',
            zjxm_sx: null,
            zjxm_jybz: '',
            zjxm_max: '',
            zjxm_min: '',
            zjxm_dw: null,
            zjxm_remark: ''
        });

        const SXOptions = ref([]);
        const DWOptions = ref([]);

        const formRules = {
            zjxm_code: [{ required: true, message: '请输入项目编码', trigger: 'blur' }],
            zjxm_name: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
            zjxm_sx: [{ required: true, message: '请选择项目类型', trigger: 'change' }],
            zjxm_jybz: [{ required: true, message: '请输入检验标准', trigger: 'blur' }],
            zjxm_max: [{ required: true, message: '请输入最大值', trigger: 'blur' }],
            zjxm_min: [{ required: true, message: '请输入最小值', trigger: 'blur' }],
            zjxm_dw: [{ required: true, message: '请选择单位', trigger: 'change' }],
        };

        const fetchTableData = () => {
            axios.get(`/api/QMS_ZJXM/GetQMS_ZJXM?state=${selectedFilter.value}`)
                .then(res => {
                    tableData.value = res.data;
                })
                .catch(err => {
                    console.error('Error fetching data:', err);
                    ElMessage.error('加载数据失败，请稍后再试');
                });
        };

        // 选中行变化
        const handleSelectionChange = (val) => {
            multipleSelection.value = val;
        };

        // 筛选条件变化
        const handleFilterChange = () => {
            fetchTableData();
        };

        // 更新状态
        const updateState = (row) => {
            ElMessageBox.confirm('改变状态, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                axios.put(`/api/QMS_ZJXM/StateChange?id=${row.zjxm_id}&state=${row.zjxm_state}`)
                    .then(response => {
                        if (response.data === true) {
                            ElMessage.success('状态已更新');
                        } else {
                            ElMessage.error('更新失败，后端返回错误');
                        }
                        fetchTableData();
                    })
                    .catch(err => {
                        console.error('Error:', err);
                        ElMessage.error('更新失败');
                    });
            }).catch(() => {
                fetchTableData();
                ElMessage.info('已取消改变');
            });
        };

        // 查询
        const query = () => {
            searchTableData(); // 假设后端支持关键字搜索，需传递searchTable.value
        };

        const searchTableData = () => {
            if (!searchTable.value) {
                fetchTableData();
                return;
            }
            const params = {
                state: selectedFilter.value,
                str: searchTable.value
            };
            axios.get('/api/QMS_ZJXM/GetQMS_ZJXM', { params })
                .then(res => {
                    tableData.value = res.data;
                })
                .catch(err => {
                    console.error('Error fetching data:', err);
                    ElMessage.error('加载数据失败，请稍后再试');
                });
        };

        // 重置
        const reset = () => {
            searchTable.value = '';
            selectedFilter.value = '1';
            fetchTableData();
        };

        // 删除单行
        const deleteRow = (row) => {
            ElMessageBox.confirm('此操作将删除该列信息, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                axios.put(`/api/QMS_ZJXM/DelQMS_ZJXM?id=${row.zjxm_id}`)
                    .then(response => {
                        if (response.data === true) {
                            ElMessage.success("删除成功");
                            fetchTableData();
                        } else {
                            ElMessage.error("删除失败：后端返回失败");
                        }
                    })
                    .catch(err => {
                        console.error('删除失败:', err);
                        ElMessage.error("删除失败：请求异常");
                    });
            }).catch(() => {
                ElMessage.info("已取消删除");
            });
        };

        const batchDelete = async () => {
            if (multipleSelection.value.length === 0) {
                ElMessage.warning("请先选择要删除的项");
                return;
            }
            try {
                await ElMessageBox.confirm('此操作将删除选中的项, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                });
                const selectedIds = multipleSelection.value.map(item => item.zjxm_id); // 确保 zjxm_id 是后端需要的字段
                const response = await axios.put('/api/QMS_ZJXM/DelQMS_ZJXMs', selectedIds, {
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                if (response.data === true) {
                    ElMessage.success("批量删除成功");
                    fetchTableData();
                } else {
                    ElMessage.error("批量删除失败：后端返回失败");
                }
            } catch (error) {
                if (error !== 'cancel') {
                    ElMessage.error("批量删除失败");
                } else {
                    ElMessage.info("已取消批量删除");
                }
            }
        };

        const openDialog = async (row) => {
            await fetchSX();  // 确保加载项目属性
            await fetchDW();  // 确保加载单位
            if (row) {
                formData.value = { ...row };
                dialogTitle.value = '编辑检验项目';
            } else {
        const now = new Date();
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1并补零
        const day = String(now.getDate()).padStart(2, '0'); // 补零

        // 生成四位随机数
        const randomNumber = Math.floor(1000 + Math.random() * 9000); // 生成1000到9999之间的随机数

        // 拼接时间字符串和随机数
        const formattedTime = `${year}${month}${day}`;
        let code = `ZJXM${formattedTime}${randomNumber}`;

                formData.value = {
                    zjxm_code: code,
                    zjxm_name: '',
                    zjxm_sx: null,
                    zjxm_jybz: '',
                    zjxm_max: '',
                    zjxm_min: '',
                    zjxm_dw: null,
                    zjxm_remark: ''
                };
                dialogTitle.value = '新增检验项目';
            }

            dialogVisible.value = true;
        };

        const submitForm = async () => {
            try {
                await formRef.value.validate(); // 验证表单

                let response;
                if (formData.value.zjxm_id) {
                    // 编辑模式，调用更新 API
                    response = await axios.put('/api/QMS_ZJXM/UpdateQMS_ZJXM', {
                        ...formData.value,
                    });
                } else {
                    // 新增模式，调用新增 API
                    response = await axios.post('/api/QMS_ZJXM/AddQMS_ZJXM', {
                        ...formData.value,
                        zjxm_id: 0, // 新增时 zjxm_id 设为 0
                        zjxm_state: formData.value.zjxm_state || 0, // 默认状态
                    });
                }

                if (response.data) {
                    ElMessage.success(formData.value.zjxm_id ? '编辑成功' : '新增成功');
                    dialogVisible.value = false;
                    fetchTableData(); // 刷新表格数据
                } else {
                    ElMessage.error('操作失败：后端返回失败');
                }
            } catch (err) {
                console.error('操作失败:', err);
                ElMessage.error('操作失败');
            }
        };

        // 获取物料分类
        const fetchSX = async () => {
            try {
                const response = await axios.get('/api/Dict/GetOneDict?id=17');
                SXOptions.value = response.data; // 正确赋值给SXOptions
                console.log(SXOptions.value);
            } catch (error) {
                console.error('获取项目属性失败:', error);
                ElMessage.error('获取项目属性失败，请稍后再试');
            }
        };

        // 获取物料分类
        const fetchDW = async () => {
            try {
                const response = await axios.get('/api/DW/GetOneDW');
                DWOptions.value = response.data; // 正确赋值给DWOptions
                console.log(DWOptions.value);
            } catch (error) {
                console.error('获取单位失败:', error);
                ElMessage.error('获取单位失败，请稍后再试');
            }
        };

        const resetForm = () => {
            formRef.value.resetFields();
        };

        onMounted(() => {
            fetchDW();
            fetchSX();
            fetchTableData();
        });

        return {
            SXOptions,
            DWOptions,
            fetchSX,
            fetchDW,
            searchTableData,
            handleSelectionChange,
            handleFilterChange,
            updateState,
            query,
            reset,
            deleteRow,
            batchDelete,
            emptyText,
            selectedFilter,
            searchTable,
            tableData,
            multipleSelection,
            dialogVisible,
            dialogTitle,
            formRef,
            formData,
            formRules,
            fetchTableData,
            openDialog,
            submitForm,
            resetForm,
        };
    },
};
</script>

<style scoped>
.container {
    display: flex;
    gap: 20px;
    height: 95%;
}

.sidebar {
    height: 100%;

}

.main {
    width: 80%;
    flex: 1;
    height: 100%;
}

.header {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 20px;
}

.eltable {
    height: 95%;
}

.letree {
    height: 100%;
}

.demo-form-inline .el-input {
    --el-input-width: 200px;
}

.demo-form-inline .el-select {
    --el-select-width: 200px;
}
</style>